<template>
  <div class="p-2">
    <transition>
      <!-- 查询区 -->
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="暂无数据"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
              v-model="queryParams.phoneNumber"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="机构查询" prop="organizationArr">
            <el-cascader
              clearable
              v-model="queryParams.organizationId"
              :props="organizationCascaderProps"
              :options="organizationTree"
              :show-all-levels="true"
              @change="handleSearchOrganizationChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <!-- <el-form-item label="机构查询" prop="organizationArr">
            <el-cascader
              clearable
              :props="organizationCascaderProps"
              :options="searchData.searchOrganizationTree"
              :show-all-levels="false"
              @change="handleSearchOrganizationChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item> -->

          <!-- <el-form-item label="年级" prop="status">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请先选择机构"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="班级" prop="memberStatus">
            <el-select
              v-model="queryParams.memberStatus"
              clearable
              placeholder="请先选择年级"
            >
              <el-option
                v-for="item in selectArr.memberStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->

          <!-- <el-form-item label="区域查询">
             <el-cascader
              :options="searchData.searchRegionTree"
              clearable
              :props="DialogData.treeProps"
              :show-all-levels="false"
              @change="handleRegionChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>  -->

          <el-form-item label="操作时间" prop="timeRange">
            <el-date-picker
              v-model="queryParams.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 按钮区 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleCreate"
              v-hasPermi="['system:user:add']"
            >
              新增
            </el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleEditUser()"
              v-hasPermi="['system:user:edit']"
            >
              编辑
            </el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['client:user:delete']"
            >
              移出班级
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['client:user:export']"
            >
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-upload
              ref="upload"
              class="upload-demo"
              action="#"
              :limit="1"
              :on-change="beforeUpload"
              :on-exceed="handleExceed"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button
                  type="info"
                  plain
                  icon="Plus"
                  @click="handleImport"
                  v-hasPermi="['client:user:import']"
                >
                  用户导入
                </el-button>
              </template>
            </el-upload>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              v-hasPermi="['system:user:import']"
            >
              <a
                href="https://fanzhiedu.oss-cn-chengdu.aliyuncs.com/template/%E5%AD%A6%E6%A0%A1%E7%94%A8%E6%88%B7%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx"
              >
                下载导入模板
              </a>
            </el-button>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getClientUserList"
          ></right-toolbar>
        </el-row>
      </template>

      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="clientUserList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column label="手机号" align="center" prop="phoneNumber" />
        <el-table-column
          label="用户昵称"
          align="center"
          prop="nickName"
          v-if="true"
        />
        <el-table-column label="注册时间" align="center" prop="createTime" />
        <el-table-column
          label="注册方式"
          align="center"
          prop="registrationMethodMsg"
        />
        <el-table-column
          label="最后在线时间"
          align="center"
          prop="lastOnlineTime"
        />
        <el-table-column
          label="累计活跃天数"
          align="center"
          prop="activityDays"
        />
        <el-table-column label="关联孩子数" align="center" prop="childNum" />
        <el-table-column
          label="是否会员"
          align="center"
          prop="memberStatusMsg"
        />
        <!-- <el-table-column label="笔记" align="center" prop="nickName" />
        <el-table-column label="评价" align="center" prop="nickName" />
        <el-table-column label="评论" align="center" prop="nickName" /> -->
        <el-table-column label="状态" align="center" prop="status">
          <template #default="{ row }: { row: ClientUserVo }">
            <el-tag :type="UserStatusTypeMap.get(row.status ?? '') ?? 'info'">
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="禁言" align="center" prop="mutedStatus">
          <template #default="{ row }: { row: ClientUserVo }">
            <el-tag
              :type="MutedStatusTypeMap.get(row.mutedStatus ?? '') ?? 'info'"
            >
              {{ row.mutedStatus === "0" ? "未禁言" : "禁言" ?? "未知" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="FolderOpened"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
            <span v-hasPermi="['system:user:edit']" class="ml-10px">
              <el-tooltip content="警告" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Warning"
                  @click="handleSendWarning(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
            <span
              v-hasPermi="['client:user:mute']"
              v-if="scope.row.mutedStatus === '0'"
              class="ml-10px"
            >
              <el-tooltip content="禁言" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="MuteNotification"
                  @click="handleBan(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
            <span v-hasPermi="['client:user:cancelMute']" v-else class="ml-10px">
              <el-tooltip content="解除禁言" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Open"
                  @click="handleCancelBan(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
            <span v-hasPermi="['course:child:removeClass']" class="ml-10px">
              <el-tooltip content="移出班级" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Right"
                  @click="handleRemove(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getClientUserList"
      />
    </el-card>

    <!-- 弹出框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="80%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form
        v-loading="dialogLoading"
        :model="currentDialogData"
        ref="dialogFormRef"
        :rules="rules"
        :inline="true"
        label-width="98px"
        class="dialogForm"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="用户昵称" prop="nickName">
              <div class="flex">
                <el-input
                  :disabled="dialogData.isDisabled"
                  v-model="currentDialogData.nickName"
                  placeholder="无"
                  clearable
                />
                <el-button
                  size="small"
                  type="primary"
                  v-hasPermi="['client:user:resetNickname']" 
                  link
                  @click="handleResetName"
                >
                  重置
                </el-button>
                <!-- <el-button
                  v-else
                  size="small"
                  type="primary"
                  link
                  @click="handleConfirm"
                >
                  确定
                </el-button> -->
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.phoneNumber"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="被举报(次)" prop="reportedNum">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.reportedNum"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="注册时间" prop="createTime">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.createTime"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="注册方式" prop="registrationMethodMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.registrationMethodMsg"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="被警告(次)" prop="warnedNum">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.warnedNum"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="最后在线" prop="lastOnlineTime">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.lastOnlineTime"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="累计活跃(天)" prop="activityDays">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.activityDays"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="被禁言(次)" prop="mutedNum">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.mutedNum"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="会员" prop="status">
              <el-select
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.memberStatus"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in selectArr.memberStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="8">
            <el-form-item label="续费次数" prop="status">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.createTime"
                placeholder="无"
                clearable
              />
            </el-form-item> -->
          <!-- </el-col> -->
        </el-row>

        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="家庭角色" prop="familyCharacterMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.familyCharacterMsg"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家长行业" prop="parentIndustryMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.parentIndustryMsg"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家长学历" prop="parentalEducationMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.parentalEducationMsg"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="家长年龄" prop="ageMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.ageMsg"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="孩子数量" prop="childNumMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.childNumMsg"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="养育类型" prop="homeStyleMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.homeStyleMsg"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <!-- <el-col :span="8">
            <el-form-item label="养育类型" prop="parentingMsg">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.parentingMsg"
                placeholder="暂无数据"
                clearable
              />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="8">
            <el-form-item label="协助抚养" prop="createTime">
              <el-input
                :disabled="dialogData.isDisabled"
                v-model="currentDialogData.createTime"
                placeholder="无"
                clearable
              />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="10">
          <el-form-item label="关联孩子">
            <el-scrollbar style="width: 100%; height: 30vh; overflow-x: auto">
              <div
                class="scrollbar-flex-content"
                v-if="
                  currentDialogData.children &&
                  currentDialogData.children.length > 0
                "
              >
                <!-- <el-card
                  class="box-card mr-5 scrollbar-demo-item w200px h150px"
                  v-for="(item, index) in currentDialogData.children"
                  :key="index"
                >
                  <div>
                    <div>姓名：{{ item.name }}</div>
                    <div v-if="item.directOrg">组织：{{ item.directOrg.name }}</div>
                    <div v-else>组织：暂无数据</div>
                    
                    <div v-if="item.grade">年级：{{ item.grade.name }}</div>
                    <div v-else>年级：暂无数据</div>
                  </div>
                </el-card> -->
                <el-card
                  class="box-card mr-5 scrollbar-demo-item h200px"
                  v-for="(item, index) in dialogData.currentDialogData.children"
                  :key="index"
                >
                  <div>
                    <div>姓名：{{ item.name }}</div>

                    <div class="flex">
                      <div>昵称：{{ item.nickName }}</div>

                      <el-button
                        size="small"
                        type="primary"
                        link
                        @click="handleResetChildName(item.id)"
                      >
                        重置
                      </el-button>
                    </div>
                    <div v-if="item.orgList && item.schoolName">
                      组织：{{ item.schoolName }}
                    </div>
                    <div v-else>组织：暂无数据</div>

                    <div v-if="item.orgList && item.gradeName">
                      年级：{{ item.gradeName }}
                    </div>
                    <div v-else>年级：暂无数据</div>

                    <div v-if="item.orgList && item.className">
                      班级：{{ item.className }}
                    </div>
                    <div v-else>班级：暂无数据</div>
                  </div>
                </el-card>
              </div>
              <!-- <el-empty v-else description="暂无数据" /> -->
              <div v-else>暂无数据</div>
            </el-scrollbar>
          </el-form-item>
        </el-row>
        <el-row :gutter="0">
          <el-form-item>
            <el-col :span="24">
              <el-tabs
                v-model="activeName"
                class="demo-tabs w70vw"
                @tab-click="handleTabClick"
              >
                <el-tab-pane label="评价" name="1">
                  <div v-if="evaluateList && evaluateList.length > 0">
                    <div
                      v-for="(item, index) in evaluateList"
                      :key="index"
                      style="border-bottom: 1px solid #999"
                    >
                      <el-row :gutter="0">
                        {{ item.updateTime }}
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="8">{{
                          item.title ? item.title : "暂无标题"
                        }}</el-col>
                        <el-col :span="16">评分：{{ item.rating }} 分</el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="16">{{ item.review }}</el-col>
                        <el-col :span="8">
                          <el-button
                            link
                            type="primary"
                            @click="handleHide(item)"
                          >
                            隐藏
                          </el-button>
                          <el-button
                            link
                            type="danger"
                            @click="handleInnerDelete(item)"
                          >
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </div>

                  <el-empty v-else description="暂无数据" />

                  <pagination
                    v-show="evaluateTotal > 0"
                    :total="evaluateTotal"
                    v-model:page="getUserEvaluateParams.pageNum"
                    v-model:limit="getUserEvaluateParams.pageSize"
                    @pagination="getEvaluateList"
                  />
                </el-tab-pane>
                <el-tab-pane label="评论" name="2">
                  <div v-if="commentList && commentList.length > 0">
                    <div
                      v-for="(item, index) in commentList"
                      :key="index"
                      style="border-bottom: 1px solid #999"
                    >
                      <el-row :gutter="0">
                        {{ item.updateTime }}
                      </el-row>
                      <!-- <el-row :gutter="20">
                        <el-col :span="8">{{
                          item.title ? item.title : "暂无标题"
                        }}</el-col>
                        <el-col :span="16"
                          >评分：{{
                            item.rating
                          }} 分</el-col
                        >
                      </el-row> -->
                      <el-row :gutter="20">
                        <el-col :span="16">{{ item.comment }}</el-col>
                        <el-col :span="8">
                          <el-button
                            link
                            type="primary"
                            @click="handleCommentHide(item)"
                          >
                            隐藏
                          </el-button>
                          <el-button
                            link
                            type="danger"
                            @click="handleInnerDelete(item)"
                          >
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </div>

                  <el-empty v-else description="暂无数据" />

                  <pagination
                    v-show="commentTotal > 0"
                    :total="commentTotal"
                    v-model:page="getCommentParams.pageNum"
                    v-model:limit="getCommentParams.pageSize"
                    @pagination="getCommentList"
                  />
                </el-tab-pane>
                <el-tab-pane label="日记" name="3">
                  <div v-if="diaryList && diaryList.length > 0">
                    <div
                      v-for="(item, index) in diaryList"
                      :key="index"
                      style="border-bottom: 1px solid #999"
                    >
                      <el-row :gutter="0">
                        {{ item.updateTime }}
                      </el-row>
                      <el-row :gutter="20" class="w30%">
                        <div class="flex flex-wrap">
                          <div
                            class="w30% ml-10px"
                            v-for="subItem in item.ossList"
                            :key="subItem"
                          >
                            <el-image
                              :zoom-rate="1.2"
                              :max-scale="7"
                              :min-scale="0.2"
                              :preview-src-list="[item.ossList]"
                              :initial-index="4"
                              style="width: 100%; height: 100%"
                              :src="subItem"
                              fit="scale-down"
                            />
                          </div>
                        </div>
                      </el-row>

                      <el-row :gutter="20">
                        <el-col :span="16">{{ item.content }}</el-col>
                        <el-col :span="8">
                          <el-button
                            link
                            type="primary"
                            @click="handleHide(item)"
                          >
                            隐藏
                          </el-button>
                          <el-button
                            link
                            type="danger"
                            @click="handleInnerDelete(item)"
                          >
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </div>

                  <el-empty v-else description="暂无数据" />

                  <pagination
                    v-show="diaryTotal > 0"
                    :total="diaryTotal"
                    v-model:page="getDiaryParams.pageNum"
                    v-model:limit="getDiaryParams.pageSize"
                    @pagination="getDiaryList"
                  />
                </el-tab-pane>
                <el-tab-pane label="笔记" name="4">
                  <div v-if="notesList && notesList.length > 0">
                    <div
                      v-for="(item, index) in notesList"
                      :key="index"
                      style="border-bottom: 1px solid #999"
                    >
                      <el-row :gutter="0">
                        {{ item.updateTime }}
                      </el-row>
                      <!-- <el-row :gutter="20" class="w30%">
                        <div class="flex flex-wrap">
                          <div
                            class="w30% ml-10px"
                            v-for="subItem in item.ossList"
                            :key="subItem"
                          >
                            <el-image
                              :zoom-rate="1.2"
                              :max-scale="7"
                              :min-scale="0.2"
                              :preview-src-list="[item.ossList]"
                              :initial-index="4"
                              style="width: 100%; height: 100%"
                              :src="subItem"
                              fit="scale-down"
                            />
                          </div>
                        </div>
                      </el-row> -->

                      <el-row :gutter="20">
                        <el-col :span="16">{{ item.content }}</el-col>
                        <el-col :span="8">
                          <el-button
                            link
                            type="primary"
                            @click="handleHide(item)"
                          >
                            隐藏
                          </el-button>
                          <el-button
                            link
                            type="danger"
                            @click="handleInnerDelete(item)"
                          >
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </div>

                  <el-empty v-else description="暂无数据" />

                  <pagination
                    v-show="notesTotal > 0"
                    :total="notesTotal"
                    v-model:page="getNotesParams.pageNum"
                    v-model:limit="getNotesParams.pageSize"
                    @pagination="getNotesList"
                  />
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-form-item>
        </el-row>

        <!-- <el-form-item label="邮箱" prop="email">
          <el-input
            :disabled="dialogData.isDisabled"
            v-model="currentDialogData.email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item> -->

        <!-- <el-form-item label="性别" prop="sex">
          <el-select
            :disabled="dialogData.isDisabled"
            v-model="currentDialogData.sex"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in selectArr.sexArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="机构" prop="organizationArr">
          <el-cascader
            v-model="currentDialogData.organizationId"
            clearable
            :props="DialogData.treeProps"
            :options="searchData.searchOrganizationTree"
            :show-all-levels="false"
            @change="dialogOrganizationChange"
          >
            <template #default="{ node }">
              <span>{{ node.label }}</span>
            </template>
          </el-cascader>
        </el-form-item> -->

        <el-form-item class="dialogFooter">
          <el-button type="primary" icon="Search" @click="addSubmit">
            提交
          </el-button>
          <el-button icon="Refresh" @click="dialog.visible = false"
            >关闭</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 警告dialog -->
    <el-dialog
      v-model="dialog.isSendWarning"
      title="请输入警告信息"
      width="40%"
      center
      :show-close="true"
      :close-on-click-modal="true"
      @close="handleCloseSendWarningDialog"
    >
      <el-form
        v-loading="dialogLoading"
        ref="warnDialogRef"
        :rules="rules"
        label-width="98px"
        class="dialogForm"
        :model="warningParams"
      >
        <el-row>
          <el-form-item label="警告信息" prop="warningMsg" class="w80%">
            <el-input
              v-model="warningParams.warningMsg"
              placeholder="请输入警告信息"
              type="textarea"
              :rows="4"
              clearable
            />
          </el-form-item>
        </el-row>

        <el-form-item label="">
          <div class="flex justify-end">
            <el-button type="primary" icon="Search" @click="handleWarning">
              发送
            </el-button>
            <el-button icon="Refresh" @click="dialog.isSendWarning = false"
              >关闭</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 禁言dialog -->
    <el-dialog
      v-model="dialog.isBan"
      title="请完善禁言信息"
      width="60%"
      center
      :show-close="true"
      :close-on-click-modal="true"
      @close="handleCloseBanDialog"
    >
      <el-form
        v-loading="dialogLoading"
        ref="banDialogRef"
        :rules="rules"
        label-width="98px"
        class="dialogForm"
        :model="banParams"
      >
        <el-row>
          <el-form-item label="解禁时间" prop="unbanTime" class="w80%">
            <el-date-picker
              v-model="banParams.unbanTime"
              type="date"
              format="YYYY-MM-DD"
              placeholder="请选择解禁时间"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
              size="default"
              @change="handleBanTimeChange"
              clearable
            />（不勾选默认永久）
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="禁言理由" prop="reason" class="w80%">
            <el-input
              v-model="banParams.reason"
              placeholder="请输入警告信息"
              type="textarea"
              :rows="4"
              clearable
            />
          </el-form-item>
        </el-row>
        <el-form-item label="">
          <div class="flex justify-end">
            <el-button type="primary" icon="Search" @click="handleConfirmBan">
              发送
            </el-button>
            <el-button icon="Refresh" @click="dialog.isBan = false"
              >关闭</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 移出班级 -->
    <el-dialog
      v-model="dialog.isRemove"
      title="选择移出班级"
      width="60%"
      center
      :show-close="true"
      :close-on-click-modal="true"
      @close="handleCloseRemoveDialog"
    >
      <el-table v-loading="removeLoading" :data="currentChildList">
        <el-table-column label="孩子姓名" align="center" prop="name" />
        <el-table-column
          label="孩子昵称"
          align="center"
          prop="nickName"
          v-if="true"
        />
        <el-table-column label="学校" align="center" prop="schoolName" />

        <el-table-column label="年级" align="center" prop="gradeName" />
        <el-table-column label="班级" align="center" prop="className" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="移出" placement="top" :enterable="false">
              <el-button link type="primary" @click="removeChild(scope.row.id)">
                <template #icon>
                  <icon-ic-baseline-remove-circle-outline />
                </template>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getClientUserList as getClientUserListApi,
  createClientUser as createClientUserApi,
  getClientUserDetail as getClientUserDetailApi,
  updateClientUser as updateClientUserApi,
  deleteClientUser as deleteClientUserApi,
  importExcel as importExcelApi,
  getEvaluateList as getEvaluateListApi,
  getCommentList as getCommentListApi,
  getDiaryList as getDiaryListApi,
  getNotesList as getNotesListApi,
  handleWarning as handleWarningApi,
  resetName as resetNameApi,
  resetChildName as resetChildNameApi,
  ban as banApi,
  cancelBan as cancelBanApi,
  removeChild as removeChildApi,
  getOrganizationTree as getOrganizationTreeApi,
  handleHide as handleHideApi,
  handleCommentHide as handleCommentHideApi,
  deleteEvaluate as deleteEvaluateApi,
  deleteComment as deleteCommentApi,
  deleteDiary as deleteDiaryApi,
  deleteNotes as deleteNotesApi,
} from "@/service/api/system/frontUser";
import { ElForm } from "element-plus";
import { download } from "@/utils/request";
import { ref } from "vue";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import {
  ClientUserInfoVo,
  ClientUserVo,
} from "@/service/api/system/frontUser/types.ts";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import { to } from "await-to-js";
import {
  UserStatusMap,
  UserStatusTypeMap,
  UserRegistrationMethodMap,
  UserMemberStatusMap,
  FamilyCharacterMap,
  ParentIndustryMap,
  ParentalEducationMap,
  ParentalAgeMap,
  ChildNumMap,
  HomeStyleMap,
  ParentingTypeMap,
  MutedStatusTypeMap,
  parentAgeMap,
} from "@/maps/system/user/userStatusMap.ts";
import { convertTimeRange } from "@/utils/request.ts";
import type { TabsPaneContext } from "element-plus";

// uploadDOM实例对象
const upload = ref<UploadInstance>();

// 上传excel到后端s
const importExcel = async (formData: any) => {
  const res = await importExcelApi(formData);
  console.log(res);
};

// 选择文件后上传
const beforeUpload = async (file: any) => {
  console.log(file);
  loading.value = true;
  const formData = new FormData();
  formData.append("file", file.raw);
  const [err, res] = await to(importExcel(formData));
  if (!err) {
    console.log(res);
    ElMessage({
      message: "导入成功",
      type: "success",
    });
    getClientUserList();
    loading.value = false;
  } else {
    ElMessage({
      message: "导入失败",
      type: "error",
    });
    getClientUserList();
    loading.value = false;
  }
};

// 选择文件超过一个时调用
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  console.log(file);
};

// 时间选择器选择的时间
const shortcuts = [
  {
    text: "一周",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
      return date;
    },
  },
  {
    text: "半个月",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 15);
      return date;
    },
  },
  {
    text: "一个月",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
      return date;
    },
  },
  {
    text: "半年",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 180);
      return date;
    },
  },
  {
    text: "一年",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 365);
      return date;
    },
  },
];

// 时间选择器不能选择的时间
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now();
};

// 列表数据s
const clientUserList = ref<ClientUserVo[]>([]);

const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref(ElForm);
const dialogFormRef = ref(ElForm);

const dialog = reactive({
  visible: false,
  title: "",
  isSendWarning: false,
  isBan: false,
  isRemove: false,
});

// 获取用户列表BO
const initGetUserList = {
  pageNum: 1,
  pageSize: 10,
  phoneNumber: "",
  status: "",
  userName: "",
  regionId: "",
  organizationId: "",
  memberStatus: "",
  orderByColumn: "createTime",
  orderType: "desc",
  params: {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  },
  timeRange: "",
};

// 初始新增用户数据
const initAddUserBO: ClientUserVo = {
  userName: "",
  email: "",
  nickName: "",
  status: "",
  phoneNumber: "",
  password: "",
  sex: "",
  id: "",
  memberStatus: "",
};

const organizationCascaderProps = {
  checkStrictly: true,
  value: "id",
};

// 所有状态
const statusArr = reactive([
  {
    value: "3",
    label: "未确认",
  },
  {
    value: "2",
    label: "禁言",
  },
  {
    value: "0",
    label: "正常",
  },
  {
    value: "1",
    label: "停用",
  },
]);

// 获取用户评价
const initGetUserEvaluateParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

// 获取用户评论
const initGetCommentParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

// 获取用户日记
const initGetDiaryParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

// 获取用户笔记
const initGetNotesParams = {
  userId: "",
  pageSize: 5,
  pageNum: 1,
};

const initGetOrganizationTree = {
  name: "",
  type: "1",
  parentId: 0,
  orderByColumn: "createTime",
  orderType: "desc",
  pageSize: 10,
  pageNum: 1,
};

// 参数，上方查询的数据
const searchData = reactive({
  queryParams: {
    ...initGetUserList,
  },
  getOrganizationTreeBO: { ...initGetOrganizationTree },
  // 获取组织参数
  organizationParams: {
    pageSize: 10,
    pageNum: 1,
    name: "",
  },
  organizationArr: [],
  rules: {
    phoneNumber: [{ required: true, message: "手机不能为空", trigger: "blur" }],
    userName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
    eMail: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
    warningMsg: [
      { required: true, message: "警告信息不能为空", trigger: "blur" },
    ],
  },
  searchRegionTree: [],
  searchOrganizationTree: [],
});

// dialog数据
const dialogData = reactive({
  currentDialogData: {
    ...initAddUserBO,
  },
  getUserEvaluateParams: { ...initGetUserEvaluateParams },
  getCommentParams: { ...initGetCommentParams },
  getDiaryParams: { ...initGetDiaryParams },
  getNotesParams: { ...initGetNotesParams },
  isDisabled: false,
  treeProps: {
    checkStrictly: true,
    value: "id",
  },
});

// dialog的select
const selectArr = reactive({
  statusArr: [
    {
      value: "3",
      label: "未确认",
    },
    {
      value: "2",
      label: "禁言",
    },
    {
      value: "0",
      label: "正常",
    },
    {
      value: "1",
      label: "停用",
    },
  ],
  sexArr: [
    {
      value: "0",
      label: "男",
    },
    {
      value: "1",
      label: "女",
    },
    {
      value: "2",
      label: "未知",
    },
  ],
  identityArr: [],
  memberStatus: [
    {
      value: "0",
      label: "非会员",
    },
    {
      value: "1",
      label: "普通会员",
    },
    {
      value: "2",
      label: "特殊会员",
    },
  ],
});

const { queryParams, rules, getOrganizationTreeBO } = toRefs(searchData);
const {
  currentDialogData,
  getUserEvaluateParams,
  getCommentParams,
  getDiaryParams,
  getNotesParams,
} = toRefs(dialogData);

const organizationTree = ref<any>([]);
/**
 * 获取组织树
 */
const getOrganizationTree = async () => {
  const [err, res] = await to<BasePageResponse<OrganizationNode>, any>(
    getOrganizationTreeApi(getOrganizationTreeBO.value),
  );
  if (!err) {
    console.log(res);
    organizationTree.value = res?.rows ?? [];
    // total.value = Number(res?.total);

    // 递归翻译状态码
    // for (const tree of organizationTree.organizationTree) {
    //   updateNodeValue(tree, "");
    // }
  }
};

/**
 * 获得客户端用户列表
 */
const getClientUserList = async (): Promise<boolean> => {
  loading.value = true;
  console.log(queryParams.value);
  const [err, res] = await to<BasePageResponse<ClientUserVo>, any>(
    getClientUserListApi(queryParams.value),
  );
  console.log(res);

  if (!err) {
    total.value = Number(res?.total ?? 0);
    clientUserList.value = res?.rows ?? [];
    clientUserList.value.forEach((item: ClientUserVo) => {
      item.statusMsg = UserStatusMap.get(item.status ?? "") ?? "未知";
      item.registrationMethodMsg =
        UserRegistrationMethodMap.get(item.registrationMethod ?? "") ?? "未知";
      item.memberStatusMsg =
        UserMemberStatusMap.get(item.memberStatus ?? "") ?? "未知";
      if (item.childNum) {
        item.childNumMsg = ChildNumMap.get(item.ageId ?? "") ?? "未知";
      }
    });
    loading.value = false;
    return true;
  }

  loading.value = false;
  return false;
};

// // 获取所有地区
// const getDefaultTree = async () => {
//   // 获取地区Tree
//   const { data } = await getDefaultRegionTreeApi();
//   searchData.searchRegionTree = data;
//   // 获取组织
//   const res = await getOrganizationApi(searchData.organizationParams);
//   searchData.searchOrganizationTree = res.data;
// };

// // 获取区域id
// const handleRegionChange = (selectedData: any) => {
//   if (selectedData && selectedData.length > 0) {
//     queryParams.value.regionId = selectedData[selectedData.length - 1];
//   }
// };

// // 获取组织id
// const handleOrganizationChange = (selectedData: any) => {
//   if (selectedData && selectedData.length > 0) {
//     queryParams.value.organizationId = selectedData[selectedData.length - 1];
//   }
// };

/** 搜索按钮操作 */
const handleQuery = () => {
  console.log(queryParams.value);
  queryParams.value.pageNum = 1;
  getClientUserList();
};

/**
 * 获取要查询的组织id
 * @param selectedData
 */
const handleSearchOrganizationChange = (selectedData: any) => {
  console.log(selectedData);

  if (selectedData && selectedData.length > 0) {
    queryParams.value.organizationId = selectedData[selectedData.length - 1];
  }
};

/**
 * 将选择的开始结束日期转换为后端需要的形式
 * @param value
 */
const handleDateRangeChange = (value: [Date | null, Date | null]) => {
  console.log(value);
  queryParams.value.params = convertTimeRange(value);
};
/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value.timeRange = "";
  queryParams.value.organizationId = "";
  queryParams.value.params = {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  };
  handleQuery();
};

/**
 * 获取多选框选中数据
 */
const handleSelectionChange = (selection: ClientUserVo[]) => {
  ids.value = selection.map((item) => item.id ?? "").filter((id) => id === "");
  // console.log('ID:!!!', ids.value[0])
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // console.log(single.value, multiple.value)
};

/**
 * 处理新增按钮
 * */
const handleCreate = async () => {
  dialog.visible = true;
  dialog.title = "新增客户端用户";
};

/**
 * 处理编辑按钮操作
 */
const handleEditUser = async (row?: ClientUserVo) => {
  // loading.value = true;
  const id = row?.id ?? ids.value[0];
  dialog.title = "编辑客户端用户";
  const [err, res] = await to<BaseResponse<ClientUserInfoVo>, any>(
    getClientUserDetailApi(id),
  );

  if (!err) {
    dialogData.currentDialogData = res?.data?.user ?? initAddUserBO;
    // 获取详细信息之后再打开dialog
    dialog.visible = true;
  }
};

/**
 * 处理删除按钮操作
 */
const handleDelete = async (row?: ClientUserVo) => {
  const _ids = row?.id || ids.value;
  const [err] = await to<BaseResponse<any>, any>(deleteClientUserApi(_ids));

  if (!err) {
    ElMessage({
      message: "删除客户端用户成功",
      type: "success",
    });
    await getClientUserList();
  }
};

/**
 * dialog中的关闭按钮
 */
const handleCloseDialog = () => {
  currentDialogData.value = Object.assign({}, initAddUserBO);
  dialog.title = "";
  loading.value = false;
  dialogData.isDisabled = false;
  activeName.value = "1";
  commentList.value = [];
  evaluateList.value = [];
};

const currentUserId = ref("");

/**
 * 处理查看用户详情
 * @param row
 */
const handleDetail = async (row: any) => {
  loading.value = true;
  dialog.title = "用户详情";
  dialogData.isDisabled = true;
  currentUserId.value = row.id ? row.id : currentUserId.value;
  const [err, res] = await to<BaseResponse<ClientUserInfoVo>, any>(
    getClientUserDetailApi(row.id ? row.id : currentUserId.value),
  );

  if (!err) {
    console.log(res?.data, dialogData.currentDialogData);
    if (res?.data) {
      dialogData.currentDialogData = res?.data;

      if (res?.data?.characterList && res?.data?.characterList.length > 0) {
        // 家庭角色
        const familyCharacterType = res.data.characterList.filter(
          (item) => item.type === "1",
        )[0];
        // 家长行业
        const parentIndustryType = res.data.characterList.filter(
          (item) => item.type === "4",
        )[0];
        // 家长学历
        const parentalEducationType = res.data.characterList.filter(
          (item) => item.type === "3",
        )[0];
        // // 家长年龄
        // const parentalAgeType = res.data.ageId.filter(
        //   (item) => item.type === "2",
        // )[0].id;
        // 孩子数量
        const childNumType = res.data.characterList.filter(
          (item) => item.type === "7",
        )[0];
        // 家庭类型
        const homeStyleType = res.data.characterList.filter(
          (item) => item.type === "2",
        );
        // 分工情况
        // const parentingType = res.data.characterList.filter(
        //   (item) => item.type === "5",
        // )[0];

        dialogData.currentDialogData.ageMsg =
          parentAgeMap.get(res?.data?.ageId ?? "") ?? "未知";
        dialogData.currentDialogData.statusMsg =
          UserStatusMap.get(dialogData.currentDialogData.status ?? "") ??
          "未知";
        dialogData.currentDialogData.registrationMethodMsg =
          UserRegistrationMethodMap.get(
            dialogData.currentDialogData.registrationMethod ?? "",
          ) ?? "未知";
        dialogData.currentDialogData.memberStatusMsg =
          UserMemberStatusMap.get(
            dialogData.currentDialogData.memberStatus ?? "",
          ) ?? "未知";
        if (familyCharacterType) {
          dialogData.currentDialogData.familyCharacterMsg =
            FamilyCharacterMap.get(familyCharacterType.id ?? "") ?? "未知";
        }
        if (parentIndustryType) {
          dialogData.currentDialogData.parentIndustryMsg =
            ParentIndustryMap.get(parentIndustryType.id ?? "") ?? "未知";
        }
        if (parentalEducationType) {
          dialogData.currentDialogData.parentalEducationMsg =
            ParentalEducationMap.get(parentalEducationType.id ?? "") ?? "未知";
        }
        if (childNumType) {
          dialogData.currentDialogData.childNumMsg =
            ChildNumMap.get(childNumType.id ?? "") ?? "未知";
        }
        if (homeStyleType) {
          dialogData.currentDialogData.homeStyleMsg = "";
          // const mock = [{ id: "11" }, { id: "19" }, { id: "15" }];
          homeStyleType.forEach((item: any, index: number) => {
            if (index === 0) {
              dialogData.currentDialogData.homeStyleMsg =
                HomeStyleMap.get(item.id ?? "") ?? "未知";
            } else {
              dialogData.currentDialogData.homeStyleMsg =
                dialogData.currentDialogData.homeStyleMsg +
                  "," +
                  HomeStyleMap.get(item.id ?? "") ?? "未知";
            }
          });
        }
        // if (parentingType) {
        //   dialogData.currentDialogData.parentingMsg =
        //     ParentingTypeMap.get(parentingType.id ?? "") ?? "未知";
        // }
      }
      if (res.data.children && res.data.children.length > 0) {
        res.data.children.forEach((item: any) => {
          if (item.orgList && item.orgList.length > 0) {
            item.orgList.forEach((subItem: any) => {
              if (subItem.type === "1") {
                item.schoolName = subItem.name;
              } else if (subItem.type === "2") {
                item.gradeName = subItem.name;
              } else {
                item.className = subItem.name;
              }
            });
          }
        });
      }
    }

    dialog.visible = true;
    dialogLoading.value = false;
    await getEvaluateList();
  }
};

// 发送警告
const handleWarning = async () => {
  console.log(warningParams.value.warningMsg);
  warnDialogRef.value.validate(async (valid: boolean) => {
    console.log(valid);

    if (valid) {
      const [err] = await to(
        handleWarningApi(currentUserId.value, warningParams.value.warningMsg),
      );
      if (!err) {
        ElMessage({
          message: "发送成功",
          type: "success",
        });
        dialog.isSendWarning = false;
      } else {
        ElMessage({
          message: "发送失败",
          type: "error",
        });
        dialog.isSendWarning = false;
      }
    }
  });
};

// const warningMsg = ref("");
// 发送警告信息
const handleSendWarning = (row: any) => {
  dialog.isSendWarning = true;
  currentUserId.value = row.id;
};

// 关闭警告dialog
const handleCloseSendWarningDialog = () => {
  currentUserId.value = "";
  warningParams.value.warningMsg = "";
};
const warnDialogRef = ref();
const dialogLoading = ref(false);
const warningParams = ref({
  warningMsg: "",
});

// 禁言参数
const banParams = ref({
  unbanTime: "" || null,
  reason: "",
  bannedUserId: "",
});
const banDialogRef = ref();
// 禁言按钮
const handleBan = (row: any) => {
  dialog.isBan = true;
  banParams.value.bannedUserId = row.id;
};

// 禁言时间改变
const handleBanTimeChange = (value: any) => {
  console.log(value);
  if (value) {
    const date = new Date(value);
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 注意，月份是从0开始的，所以我们需要加1
    let day = date.getDate();
    banParams.value.unbanTime = `${year}-${month < 10 ? "0" + month : month}-${
      day < 10 ? "0" + day : day
    } 00:00:00`;
  } else {
    banParams.value.unbanTime = null;
  }
};

// 关闭禁言dialog
const handleCloseBanDialog = () => {
  // 重置
  banParams.value = {
    unbanTime: "",
    reason: "",
    bannedUserId: "",
  };
};

// 禁言提交按钮
const handleConfirmBan = async () => {
  banDialogRef.value.validate(async (valid: boolean) => {
    if (valid) {
      console.log(banParams.value);
      const [err, res] = await to(banApi(banParams.value));
      if (!err) {
        console.log(res);
        ElMessage({
          message: "禁言成功",
          type: "success",
        });
        getClientUserList();
        dialog.isBan = false;
      } else {
        ElMessage({
          message: "禁言失败",
          type: "error",
        });
        getClientUserList();
        dialog.isBan = false;
      }
    }
  });
};

// 解除禁言按钮
const handleCancelBan = async (row: any) => {
  console.log(row);
  const [err] = await to<string, string>(
    ElMessageBox.confirm("是否确定解除该用户的禁言状态？", "警告", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }),
  );
  if (!err) {
    const [err] = await to(cancelBanApi(row.id));
    if (!err) {
      ElMessage({
        message: "解除成功",
        type: "success",
      });
      getClientUserList();
    } else {
      ElMessage({
        message: "解除失败",
        type: "error",
      });
      getClientUserList();
    }
  } else {
    ElMessage({
      message: "取消成功",
      type: "success",
    });
    getClientUserList();
  }
};

const currentChildList = ref([]);

// 移出孩子
const removeChild = async (id: string) => {
  const [err] = await to<string, string>(
    ElMessageBox.confirm("是否确定移出该小孩？", "警告", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }),
  );
  if (!err) {
    const [err] = await to(removeChildApi(id));
    if (!err) {
      ElMessage({
        message: "移出成功",
        type: "success",
      });
      console.log(currentUserId.value);

      const [err, res] = await to<BaseResponse<ClientUserInfoVo>, any>(
        getClientUserDetailApi(currentUserId.value),
      );
      if (!err) {
        if (res?.data.children && res?.data.children.length > 0) {
          // 如果有孩子
          console.log("有孩子");
          if (res.data.children && res.data.children.length > 0) {
            res.data.children.forEach((item: any) => {
              if (item.orgList && item.orgList.length > 0) {
                item.orgList.forEach((subItem: any) => {
                  if (subItem.type === "1") {
                    item.schoolName = subItem.name;
                  } else if (subItem.type === "2") {
                    item.gradeName = subItem.name;
                  } else {
                    item.className = subItem.name;
                  }
                });
              }
            });
          }
          currentChildList.value = res?.data.children;
        } else {
          console.log("没孩子");
          dialog.isRemove = false;
        }
      }
      getClientUserList();
    } else {
      ElMessage({
        message: "移出失败",
        type: "error",
      });
      getClientUserList();
    }
  } else {
    ElMessage({
      message: "取消成功",
      type: "info",
    });
    getClientUserList();
  }
};

// 移出班级按钮
const handleRemove = async (row: any) => {
  console.log(row);
  currentUserId.value = row.id;
  if (row.childNum && row.childNum > 0) {
    const [err, res] = await to<BaseResponse<ClientUserInfoVo>, any>(
      getClientUserDetailApi(row.id ? row.id : currentUserId.value),
    );
    if (!err) {
      if (res?.data.children && res?.data.children.length > 0) {
        // 有孩子
        console.log(res);
        if (row.childNum === 1) {
          // 只有一个孩子
          console.log("1");
          const [err] = await to<string, string>(
            ElMessageBox.confirm(
              "该用户只关联一个孩子，是否确定移出小孩？",
              "警告",
              {
                type: "warning",
                confirmButtonText: "确认",
                cancelButtonText: "取消",
              },
            ),
          );
          if (!err) {
            await removeChild(res?.data.children[0].id);
          } else {
            ElMessage({
              message: "取消成功",
              type: "info",
            });
          }
        } else {
          // 多个孩子
          dialog.isRemove = true;
          // 遍历获取年级班级学校
          if (res.data.children && res.data.children.length > 0) {
            res.data.children.forEach((item: any) => {
              if (item.orgList && item.orgList.length > 0) {
                item.orgList.forEach((subItem: any) => {
                  if (subItem.type === "1") {
                    item.schoolName = subItem.name;
                  } else if (subItem.type === "2") {
                    item.gradeName = subItem.name;
                  } else {
                    item.className = subItem.name;
                  }
                });
              }
            });
          }
          console.log(res?.data);

          currentChildList.value = res?.data.children;
          console.log(currentChildList.value);
        }
      }
    } else {
      ElMessage({
        message: "获取用户详情失败",
        type: "error",
      });
    }
  } else {
    ElMessage({
      message: "该用户没有关联孩子，不能移出！！",
      type: "warning",
    });
  }
};

// 关闭小孩列表dialog
const handleCloseRemoveDialog = () => {
  currentChildList.value = [];
  currentUserId.value = "";
};

// 重置用户名称
const handleResetName = async () => {
  dialogLoading.value = true;
  const [err] = await to(resetNameApi(currentUserId.value));
  if (!err) {
    ElMessage({
      message: "重置成功",
      type: "success",
    });
    await handleDetail(currentUserId.value);
  } else {
    ElMessage({
      message: "重置失败",
      type: "error",
    });
  }
};

// 重置小孩名称
const handleResetChildName = async (id: string) => {
  const [err] = await to(resetChildNameApi(id));
  if (!err) {
    ElMessage({
      message: "重置成功",
      type: "success",
    });
    await handleDetail(currentUserId.value);
  } else {
    ElMessage({
      message: "重置失败",
      type: "error",
    });
  }
};

const activeName = ref("1");
// 切换tab按钮
const handleTabClick = async (tab: TabsPaneContext) => {
  if (tab.props.name === "1") {
    // 评价
    activeName.value = "1";
    console.log(activeName.value);

    await getEvaluateList();
  } else if (tab.props.name === "2") {
    // 评论
    activeName.value = "2";
    console.log(activeName.value);

    await getCommentList();
  } else if (tab.props.name === "3") {
    // 日记
    activeName.value = "3";
    console.log(activeName.value);

    await getDiaryList();
  } else {
    // 笔记
    activeName.value = "4";
    console.log(activeName.value);

    await getNotesList();
  }
};
/**
 * 除了评论以外的隐藏
 * @param item 每个节点信息
 */
const handleHide = async (item: any) => {
  console.log(item, activeName.value);
  const [err, res] = await to(handleHideApi(item.id));
  if (!err) {
    console.log(res);
    ElMessage({
      type: "success",
      message: "隐藏成功！",
    });
    if (activeName.value === "1") {
      await getEvaluateList();
    } else if (activeName.value === "3") {
      await getDiaryList();
    } else {
      await getNotesList();
    }
  } else {
    ElMessage({
      type: "error",
      message: "隐藏失败！",
    });
  }
};
/**
 * 隐藏评论
 * @param item 每个节点信息
 */
const handleCommentHide = async (item: any) => {
  item.status = !item.status;
  const [err] = await to(handleCommentHideApi(item.status, item.id));
  if (!err) {
    ElMessage({
      type: "success",
      message: "隐藏成功！",
    });
    getCommentList();
  } else {
    ElMessage({
      type: "error",
      message: "隐藏失败！",
    });
    getCommentList();
  }
};

// 删除评论
const handleInnerDelete = async (item: any) => {
  if (activeName.value === "1") {
    const [err] = await to(deleteEvaluateApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getEvaluateList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getEvaluateList();
    }
  } else if (activeName.value === "2") {
    const [err] = await to(deleteCommentApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getCommentList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getCommentList();
    }
  } else if (activeName.value === "3") {
    const [err] = await to(deleteDiaryApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getDiaryList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getDiaryList();
    }
  } else {
    const [err] = await to(deleteNotesApi(item.id));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      await getNotesList();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败！",
      });
      await getNotesList();
    }
  }
};

const evaluateList = ref([]);
const evaluateTotal = ref(0);
// 获取用户评价列表
const getEvaluateList = async () => {
  getUserEvaluateParams.value.userId = currentUserId.value;
  const [err, res] = await to(getEvaluateListApi(getUserEvaluateParams.value));
  if (!err) {
    console.log(res);
    evaluateList.value = res.rows;
    evaluateTotal.value = Number(res.total);
  }
};

const commentList = ref([]);
const commentTotal = ref(0);
// 获取用户评论列表
const getCommentList = async () => {
  getCommentParams.value.userId = currentUserId.value;
  const [err, res] = await to(getCommentListApi(getCommentParams.value));
  if (!err) {
    console.log(res);

    commentList.value = res.rows ?? [];
    commentTotal.value = Number(res.total);
  }
};

const diaryList = ref([]);
const diaryTotal = ref(0);
// 获取用户日记列表
const getDiaryList = async () => {
  getDiaryParams.value.userId = currentUserId.value;
  const [err, res] = await to(getDiaryListApi(getDiaryParams.value));
  if (!err) {
    console.log(res);
    diaryList.value = res.rows ?? [];
    // diaryList.value.forEach((item: any) => {
    //   if (diaryList.value.ossList && diaryList.value.ossList.length > 0) {
    //   ossList.value = diaryList.value.ossList;
    // } else {
    //   ossList.value = []
    // }
    // })

    diaryTotal.value = Number(res.total);
  }
};
const notesList = ref([]);
const notesTotal = ref(0);
// 获取用户日记列表
const getNotesList = async () => {
  getNotesParams.value.userId = currentUserId.value;
  const [err, res] = await to(getNotesListApi(getNotesParams.value));
  if (!err) {
    console.log(res);
    notesList.value = res.rows ?? [];
    notesTotal.value = Number(res.total);
  }
};
/**
 * 提交按钮
 */
const addSubmit = () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    console.log(currentDialogData.value);

    if (valid) {
      if (currentDialogData.value.id) {
        // 编辑修改用户
        await updateClientUserApi(currentDialogData.value);
        ElMessage({
          message: "用户修改成功",
          type: "success",
        });
        getClientUserList();
      } else {
        await createClientUserApi(currentDialogData.value);
        currentDialogData.value = Object.assign({}, initAddUserBO);
        ElMessage({
          message: "用户添加成功",
          type: "success",
        });
        getClientUserList();
      }
      dialog.visible = false;
      await getClientUserList();
    }
  });
};

// 获取导入模板
// const getExportTemplate = async () => {
//   const res = await getExportTemplateApi()
//   console.log(res);
// }

/**
 * 导出按钮操作
 */
const handleExport = () => {
  download(
    "/system/user/export",
    { ...queryParams.value },
    `demo_${new Date().getTime()}.xlsx`,
  );
};

// 上传到oss

/**
 * 导入按钮
 */
const handleImport = () => {};

onMounted(() => {
  getClientUserList();
  getOrganizationTree();
  // getDefaultTree();
});
</script>

<style scoped lang="scss">
.el-date-pickerv {
  width: 900px;
}

.dialogForm {
  padding: 0 0 0 45px;

  // background-color: pink;
  .el-input {
    width: 219px;
  }

  .el-select {
    width: 219px;
  }
}

.dialogFooter {
  margin: 40px 0 0 450px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .setting {
    margin-left: 100px;
  }
}

.scrollbar-flex-content {
  display: flex;
  /* width: 60%; */
}

.scrollbar-demo-item {
  flex-shrink: 0;
  border-radius: 4px;
}

img {
  flex: 1 0 33%; /* 这将使得每行中的图片数量尽可能保持为3个，但也会根据屏幕宽度进行调整 */
  margin: 10px; /* 调整间距 */
  max-width: 100%; /* 确保图片不会超出容器 */
}
</style>
